<!-- eslint-disable vue/no-deprecated-slot-attribute -->
<!-- eslint-disable vue/no-deprecated-slot-scope-attribute -->
<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="logistics-management-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dealer' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>物流管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 物流列表 -->
    <el-card class="content-card">
      <div slot="header" class="card-header">
        <span>物流信息列表</span>
      </div>

<!--      &lt;!&ndash; 搜索区域 &ndash;&gt;-->
<!--      <el-row :gutter="20" class="search-area">-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入订单号" v-model="queryParams.orderNumber" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchLogistics"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--        <el-col :span="6">-->
<!--          <el-input placeholder="请输入物流单号" v-model="queryParams.logisticsNumber" clearable>-->
<!--            <el-button slot="append" icon="el-icon-search" @click="searchLogistics"></el-button>-->
<!--          </el-input>-->
<!--        </el-col>-->
<!--&lt;!&ndash;        <el-col :span="6">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-select v-model="queryParams.deliveryStatus" placeholder="物流状态" clearable style="width: 100%">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option label="待发货" value="待发货"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option label="已发货" value="已发货"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option label="运输中" value="运输中"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option label="已送达" value="已送达"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option label="已签收" value="已签收"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-select>&ndash;&gt;-->
<!--&lt;!&ndash;        </el-col>&ndash;&gt;-->
<!--        <el-col :span="6">-->
<!--          <el-button type="primary" @click="searchLogistics">搜索</el-button>-->
<!--&lt;!&ndash;          <el-button @click="resetQuery">重置</el-button>&ndash;&gt;-->
<!--        </el-col>-->
<!--      </el-row>-->

      <!-- 表格 -->
      <el-table :data="logisticsList" border stripe style="width: 100%">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="orderNumber" label="订单号" width="120"></el-table-column>
        <el-table-column prop="logisticsNumber" label="物流单号" width="120"></el-table-column>
        <el-table-column prop="logisticsCompany" label="物流公司" width="120"></el-table-column>
<!--        <el-table-column prop="productName" label="产品名称" width="120"></el-table-column>-->
        <el-table-column prop="shipDate" label="发货日期" width="180"></el-table-column>
        <el-table-column prop="startLocation" label="发货地址" width="120"></el-table-column>
        <el-table-column prop="toLocation" label="收货地址" width="120"></el-table-column>
        <!--        <el-table-column prop="estimatedDeliveryDate" label="预计送达日期" width="180"></el-table-column>-->
<!--        <el-table-column prop="deliveryStatus" label="物流状态" width="100">-->
<!--          <template v-slot="scope">-->
<!--            <el-tag :type="getDeliveryStatusType(scope.row.deliveryStatus)">{{ scope.row.deliveryStatus }}</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="操作" width="240">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-view" @click.prevent="handleView(scope.row)">详情</el-button>
<!--            <el-button type="success" size="mini" icon="el-icon-edit" @click.prevent="openShipDialog(scope.row)" v-if="scope.row.deliveryStatus === '待发货'">发货</el-button>-->
<!--            <el-button type="warning" size="mini" icon="el-icon-location" @click.prevent="trackLogistics(scope.row)" v-if="scope.row.deliveryStatus !== '待发货'">-->
<!--              物流追踪-->
<!--              <span style="display: none;">{{ console.log('物流追踪按钮状态:', scope.row.deliveryStatus) }}</span>-->
<!--            </el-button>-->
<!--            <el-button type="info" size="mini" icon="el-icon-printer" @click.prevent="printShippingLabel(scope.row)" v-if="scope.row.deliveryStatus !== '待发货'">-->
<!--              打印面单-->
<!--              <span style="display: none;">{{ console.log('打印面单按钮状态:', scope.row.deliveryStatus) }}</span>-->
<!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 物流详情对话框 -->
<!--    <el-dialog title="物流详情" v-model="detailDialogVisible" width="60%" :before-close="() => detailDialogVisible = false">-->
<!--      <el-descriptions :column="2" border>-->
<!--        <el-descriptions-item label="订单号">{{ currentLogistics.orderNumber }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="物流单号">{{ currentLogistics.logisticsNumber }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="物流公司">{{ currentLogistics.logisticsCompany }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="产品名称">{{ currentLogistics.productName }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="发货日期">{{ currentLogistics.shipDate }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="预计送达日期">{{ currentLogistics.estimatedDeliveryDate }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="实际送达日期">{{ currentLogistics.actualDeliveryDate || '未送达' }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="物流状态">-->
<!--          <el-tag :type="getDeliveryStatusType(currentLogistics.deliveryStatus)">{{ currentLogistics.deliveryStatus }}</el-tag>-->
<!--        </el-descriptions-item>-->
<!--        <el-descriptions-item label="司机姓名">{{ currentLogistics.driverName }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="司机电话">{{ currentLogistics.driverPhone }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="车牌号">{{ currentLogistics.vehicleNumber }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="运输条件">{{ currentLogistics.transportConditions }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="起始地点">{{ currentLogistics.startLocation }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="目的地">{{ currentLogistics.destination }}</el-descriptions-item>-->
<!--        <el-descriptions-item label="签收凭证" v-if="currentLogistics.signatureReceipt">-->
<!--          <el-image-->
<!--            style="width: 100px; height: 100px"-->
<!--            :src="currentLogistics.signatureReceipt"-->
<!--            :preview-src-list="[currentLogistics.signatureReceipt]">-->
<!--          </el-image>-->
<!--        </el-descriptions-item>-->
<!--      </el-descriptions>-->

<!--      <template #footer>-->
<!--        <div class="dialog-footer">-->
<!--          <el-button @click="detailDialogVisible = false">关 闭</el-button>-->
<!--        </div>-->
<!--      </template>-->
<!--    </el-dialog>-->


    <!-- 物流详情对话框 -->
    <el-dialog title="物流详情" v-model="detailDialogVisible" width="60%" :before-close="() => detailDialogVisible = false">
      <el-form :model="currentLogistics" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单号">
              <el-input v-model="currentLogistics.orderNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物流单号">
              <el-input v-model="currentLogistics.logisticsNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物流公司">
              <el-input v-model="currentLogistics.logisticsCompany"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="产品名称">-->
<!--              <el-input v-model="currentLogistics.productName"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="发货日期">
              <!--              <el-date-picker v-model="currentLogistics.shipDate" type="date" placeholder="选择日期"></el-date-picker>-->
              <el-date-picker
                  v-model="currentLogistics.shipDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row :gutter="20">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="发货日期">-->
<!--&lt;!&ndash;              <el-date-picker v-model="currentLogistics.shipDate" type="date" placeholder="选择日期"></el-date-picker>&ndash;&gt;-->
<!--              <el-date-picker-->
<!--                  v-model="currentLogistics.shipDate"-->
<!--                  type="date"-->
<!--                  placeholder="选择日期"-->
<!--                  value-format="YYYY-MM-DD"-->
<!--              ></el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--&lt;!&ndash;          <el-col :span="12">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-form-item label="预计送达日期">&ndash;&gt;-->
<!--&lt;!&ndash;              <el-date-picker v-model="currentLogistics.estimatedDeliveryDate" type="date" placeholder="选择日期"></el-date-picker>&ndash;&gt;-->
<!--&lt;!&ndash;            </el-form-item>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-col>&ndash;&gt;-->
<!--        </el-row>-->

<!--        <el-row :gutter="20">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="实际送达日期">-->
<!--              <el-date-picker v-model="currentLogistics.actualDeliveryDate" type="date" placeholder="选择日期"></el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="物流状态">-->
<!--              <el-select v-model="currentLogistics.deliveryStatus">-->
<!--                <el-option label="已发货" value="已发货"></el-option>-->
<!--                <el-option label="运输中" value="运输中"></el-option>-->
<!--                <el-option label="已送达" value="已送达"></el-option>-->
<!--                <el-option label="已签收" value="已签收"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-row :gutter="20">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="司机姓名">-->
<!--              <el-input v-model="currentLogistics.driverName"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="司机电话">-->
<!--              <el-input v-model="currentLogistics.driverPhone"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

<!--        <el-row :gutter="20">-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="车牌号">-->
<!--              <el-input v-model="currentLogistics.vehicleNumber"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="运输条件">-->
<!--              <el-input v-model="currentLogistics.transportConditions"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货地址">
              <el-input v-model="currentLogistics.startLocation"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址">
              <el-input v-model="currentLogistics.toLocation"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-form-item label="签收凭证" v-if="currentLogistics.signatureReceipt">-->
<!--          <el-image-->
<!--              style="width: 100px; height: 100px"-->
<!--              :src="currentLogistics.signatureReceipt"-->
<!--              :preview-src-list="[currentLogistics.signatureReceipt]">-->
<!--          </el-image>-->
<!--          <el-upload-->
<!--              action="your-upload-api"-->
<!--              :show-file-list="false"-->
<!--              :on-success="handleUploadSuccess">-->
<!--            <el-button type="primary">更换图片</el-button>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
      </el-form>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="detailDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlerSubmit()">提交</el-button>
    </span>
      </template>
    </el-dialog>


























































    <!-- 发货对话框 -->
    <el-dialog title="发货信息" v-model="shipDialogVisible" width="60%" :before-close="resetShipForm">
      <el-form :model="shipForm" :rules="shipRules" ref="shipFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单号" prop="orderNumber">
              <el-input v-model="shipForm.orderNumber" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物流公司" prop="logisticsCompany">
              <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司" style="width: 100%">
                <el-option label="顺丰快递" value="顺丰快递"></el-option>
                <el-option label="中通快递" value="中通快递"></el-option>
                <el-option label="圆通快递" value="圆通快递"></el-option>
                <el-option label="申通快递" value="申通快递"></el-option>
                <el-option label="韵达快递" value="韵达快递"></el-option>
                <el-option label="德邦物流" value="德邦物流"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物流单号" prop="logisticsNumber">
              <el-input v-model="shipForm.logisticsNumber" placeholder="请输入物流单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输条件" prop="transportConditions">
              <el-select v-model="shipForm.transportConditions" placeholder="请选择运输条件" style="width: 100%">
                <el-option label="常温运输" value="常温运输"></el-option>
                <el-option label="冷链运输" value="冷链运输"></el-option>
                <el-option label="恒温运输" value="恒温运输"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货日期" prop="shipDate">
              <el-date-picker
                v-model="shipForm.shipDate"
                type="datetime"
                placeholder="选择发货日期时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="预计送达日期" prop="estimatedDeliveryDate">-->
<!--              <el-date-picker-->
<!--                v-model="shipForm.estimatedDeliveryDate"-->
<!--                type="datetime"-->
<!--                placeholder="选择预计送达日期时间"-->
<!--                style="width: 100%">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="shipForm.driverName" placeholder="请输入司机姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机电话" prop="driverPhone">
              <el-input v-model="shipForm.driverPhone" placeholder="请输入司机电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="vehicleNumber">
              <el-input v-model="shipForm.vehicleNumber" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始地点" prop="startLocation">
              <el-input v-model="shipForm.startLocation" placeholder="请输入起始地点"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="目的地" prop="destination">
          <el-input v-model="shipForm.destination" placeholder="请输入目的地"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitShipForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物流追踪对话框 -->
    <el-dialog title="物流追踪" v-model="trackDialogVisible" width="50%" :before-close="() => trackDialogVisible = false">
      <el-steps direction="vertical" :active="trackData.length">
        <el-step
          v-for="(item, index) in trackData"
          :key="index"
          :title="item.status"
          :description="item.time + ' ' + item.location + ' ' + item.description">
        </el-step>
      </el-steps>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="trackDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { logisticsAPI } from '@/api/api'
import axios from "axios";

export default {
  name: 'LogisticsManagementView',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: '',
        logisticsNumber: '',
        deliveryStatus: ''
      },
      // 总记录数
      total: 0,
      // 物流列表
      logisticsList: [],
      // 物流详情对话框显示状态
      detailDialogVisible: false,
      // 当前选中的物流
      currentLogistics: {},
      // 发货对话框显示状态
      shipDialogVisible: false,
      // 发货表单
      shipForm: {
        orderId: null,
        orderNumber: '',
        logisticsCompany: '',
        logisticsNumber: '',
        transportConditions: '',
        shipDate: '',
        estimatedDeliveryDate: '',
        driverName: '',
        driverPhone: '',
        vehicleNumber: '',
        startLocation: '',
        destination: ''
      },
      // 发货表单校验规则
      shipRules: {
        logisticsCompany: [
          { required: true, message: '请选择物流公司', trigger: 'change' }
        ],
        logisticsNumber: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        transportConditions: [
          { required: true, message: '请选择运输条件', trigger: 'change' }
        ],
        shipDate: [
          { required: true, message: '请选择发货日期', trigger: 'change' }
        ],
        estimatedDeliveryDate: [
          { required: true, message: '请选择预计送达日期', trigger: 'change' }
        ],
        driverName: [
          { required: true, message: '请输入司机姓名', trigger: 'blur' }
        ],
        driverPhone: [
          { required: true, message: '请输入司机电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        startLocation: [
          { required: true, message: '请输入起始地点', trigger: 'blur' }
        ],
        destination: [
          { required: true, message: '请输入目的地', trigger: 'blur' }
        ]
      },
      // 物流追踪对话框显示状态
      trackDialogVisible: false,
      // 物流追踪数据
      trackData: [],
      // 加载状态
      loading: false
    }
  },
  created() {
    this.getLogisticsList()
    // 检查URL中是否有orderId参数，如果有则直接打开发货对话框
    const orderId = this.$route.query.orderId
    if (orderId) {
      this.handleShipByOrderId(orderId)
    }
  },

  methods: {
    formatDate(dateArray) {
      return `${dateArray[0]}年${dateArray[1]}月${dateArray[2]}日`;
    },
    handlerSubmit(){
      console.log(this.currentLogistics)
      // 发送 POST 请求
      axios.post("/api/logistics/insert", this.currentLogistics)
          .then(response => {
            console.log("插入成功:", response.data);
          })
          .catch(error => {
            console.error("插入失败:", error.response.data);
          });
     this.detailDialogVisible=false;

    },
    // 获取物流列表
    async getLogisticsList() {
      try {
        console.log('开始获取物流列表, 查询参数:', this.queryParams);
        this.loading = true;
        
        // 调用物流API获取数据
        const response = await logisticsAPI.getLogistics(this.queryParams);
        console.log('物流API响应:', response);
        console.log(response.data)
        
        if (response && response.data && response.data.content) {
          // 使用API返回的真实数据
          this.logisticsList = response.data.content || [];
          // 或者方法2：使用for循环
          for (let i = 0; i < this.logisticsList.length; i++) {
            if (this.logisticsList[i].shipDate) {
              this.logisticsList[i].shipDate = this.formatDate(this.logisticsList[i].shipDate);
              // this.logisticsList[i].estimatedDeliveryDate = this.formatDateTime(this.arrayToDate(this.logisticsList[i].estimatedDeliveryDate));

            }
          }

          this.total = response.data.totalElements || 0;
          console.log('物流列表数据:', this.logisticsList);
          
          if (this.logisticsList.length === 0) {
            ElMessage.info('暂无物流数据');
          }
        } else {
          // API返回失败或没有数据
          this.logisticsList = [];
          this.total = 0;
          ElMessage.warning('获取物流列表失败，请检查网络连接或联系管理员');
        }
      } catch (error) {
        console.error('获取物流列表失败:', error);
        ElMessage.error('获取物流列表失败: ' + (error.message || '未知错误'));
        this.logisticsList = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },
    // 获取物流状态对应的类型
    getDeliveryStatusType(status) {
      switch (status) {
        case '待发货':
          return 'info'
        case '已发货':
          return 'primary'
        case '运输中':
          return 'warning'
        case '已送达':
          return 'success'
        case '已签收':
          return 'success'
        default:
          return 'info'
      }
    },
    // 将数组转换为Date对象
    arrayToDate(dateArray) {
  if (!dateArray || dateArray.length < 6) return null;
  return new Date(
      dateArray[0], // 年
      dateArray[1] - 1, // 月 (0-11)
      dateArray[2], // 日
      dateArray[3], // 时
      dateArray[4], // 分
      dateArray[5]  // 秒
  );
 },
  formatDateTime(date) {
  if (!date) return null;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  // 或者返回其他格式如："2025/04/16 17:16:37"
},
    // 搜索物流
    searchLogistics() {
      this.queryParams.pageNum = 1
      this.getLogisticsList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderNumber: '',
        logisticsNumber: '',
        deliveryStatus: ''
      }
      this.getLogisticsList()
    },
    // 处理每页数量变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getLogisticsList()
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getLogisticsList()
    },
    // 查看详情
    async handleView(row) {
      try {
        console.log('查看详情', row);
        // 先显示对话框，避免网络延迟导致的无反应感
        this.currentLogistics = row;
        this.detailDialogVisible = true;
        console.log('detailDialogVisible设置为:', this.detailDialogVisible);

        // 然后尝试从API获取更详细的信息
        const response = await logisticsAPI.getLogisticsById(row.id);

        if (response && response.success) {
          // 如果API成功，更新详情数据
          this.currentLogistics = response.data;

          this.currentLogistics.shipDate= this.formatDateTime(this.arrayToDate(this.currentLogistics.shipDate));
          this.currentLogistics.estimatedDeliveryDate=this.formatDateTime(this.arrayToDate(this.currentLogistics.estimatedDeliveryDate));


          console.log('API返回的物流详情:', response.data);
        } else {
          // API失败时保持使用原始数据
          console.warn('获取物流详情失败:', response ? response.message : '未知错误');
        }
      } catch (error) {
        console.error('查看物流详情失败:', error);
        // 出错时不再显示错误消息，因为基本信息已经显示
      }
    },
    // 生成随机物流单号
    generateLogisticsNumber() {
      // 生成形如 SF1234567890 的物流单号
      const prefix = ['SF', 'ZT', 'YT', 'ST', 'YD', 'DB'][Math.floor(Math.random() * 6)];
      const numbers = Math.floor(1000000000 + Math.random() * 9000000000);
      return prefix + numbers.toString();
    },
    // 打开发货对话框
    openShipDialog(row) {
      console.log('打开发货对话框', row);
      this.currentRow = row;
      this.shipForm = {
        orderId: row.id,
        orderNumber: row.orderNumber,
        logisticsCompany: '顺丰速运', // 设置默认物流公司
        logisticsNumber: this.generateLogisticsNumber(), // 生成随机物流单号
        transportConditions: '',
        shipDate: new Date(), // 设置默认发货日期为今天
        estimatedDeliveryDate: new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000), // 设置默认预计送达日期为两天后
        driverName: '',
        driverPhone: '',
        vehicleNumber: '',
        startLocation: '',
        destination: row.destination || '' // 从订单中获取目的地
      };
      this.shipDialogVisible = true;
      console.log('shipDialogVisible状态:', this.shipDialogVisible);
    },
    // 根据订单ID处理发货
    handleShipByOrderId(orderId) {
      // 实际项目中应该根据订单ID查询订单信息
      // 这里简单模拟
      const order = {
        id: orderId,
        orderNumber: 'DD20250002'
      }
      this.openShipDialog(order)
    },
    // 提交发货表单
    submitShipForm() {
      console.log('提交发货表单', this.shipForm);
      this.$refs.shipFormRef.validate(async (valid) => {
        if (valid) {
          try {
            // 调用API发货
            const response = await logisticsAPI.shipOrder(this.shipForm);
            console.log('发货响应:', response);

            if (response && response.success) {
              ElMessage.success('发货信息已保存');
              this.shipDialogVisible = false;
              this.resetShipForm();
              this.getLogisticsList(); // 刷新物流列表
            } else {
              ElMessage.error(response?.message || '保存发货信息失败');
            }
          } catch (error) {
            console.error('发货操作发生错误:', error);
            ElMessage.error('发货操作失败: ' + (error.response?.data?.message || error.message || '未知错误'));
          }
        } else {
          ElMessage.warning('请完善发货信息');
          return false;
        }
      });
    },
    // 重置发货表单
    resetShipForm() {
      try {
        console.log('重置发货表单');
        if (this.$refs.shipFormRef) {
          this.$refs.shipFormRef.resetFields();
        }
        this.shipForm = {
          orderId: null,
          orderNumber: '',
          logisticsCompany: '',
          logisticsNumber: '',
          transportConditions: '',
          shipDate: new Date(),
          estimatedDeliveryDate: new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000),
          driverName: '',
          driverPhone: '',
          vehicleNumber: '',
          startLocation: '',
          destination: ''
        }
        // 设置对话框为关闭状态
        this.shipDialogVisible = false;
      } catch (error) {
        console.error('重置表单错误:', error);
      }
    },
    // 物流追踪
    async trackLogistics(row) {
      try {
        console.log('查询物流信息，物流单号:', row.logisticsNumber);
        
        // 先显示对话框
        this.trackDialogVisible = true;
        console.log('trackDialogVisible设置为:', this.trackDialogVisible);
        
        // 设置加载状态
        this.trackData = [
          {
            time: '正在查询中...',
            location: '',
            status: '查询中',
            description: '正在获取物流轨迹数据，请稍候...'
          }
        ];
        
        if (!row.logisticsNumber) {
          ElMessage.warning('物流单号不存在，无法查询物流信息');
          this.trackData = [];
          return;
        }
        
        // 调用物流追踪API获取真实数据
        const response = await logisticsAPI.trackLogistics(row.logisticsNumber);
        
        if (response && response.success) {
          this.trackData = response.data || [];
          console.log('获取到物流追踪数据:', this.trackData);
          
          if (this.trackData.length === 0) {
            ElMessage.info('暂无物流轨迹信息');
          }
        } else {
          // API返回失败
          this.trackData = [];
          ElMessage.warning('获取物流轨迹失败: ' + (response ? response.message : '未知错误'));
        }
      } catch (error) {
        console.error('查询物流轨迹失败:', error);
        ElMessage.error('查询物流轨迹失败: ' + (error.message || '未知错误'));
        this.trackData = [];
      }
    },
    // 打印物流面单
    async printShippingLabel(row) {
      try {
        console.log('打印物流面单，ID:', row.id);
        
        if (!row.logisticsNumber) {
          ElMessage.warning('物流单号不存在，无法打印物流面单');
          return;
        }
        
        // 无论是否有物流单号，都给用户一个即时反馈
        ElMessage({
          message: '正在准备打印面单...',
          type: 'info',
          duration: 1000
        });
        
        // 调用打印API获取真实数据
        const response = await logisticsAPI.printShippingLabel(row.id);
        
        if (response) {
          try {
            // 处理二进制流，创建blob URL并打开新窗口
            const blob = new Blob([response], { type: 'application/pdf' });
            const url = window.URL.createObjectURL(blob);
            window.open(url, '_blank');
            ElMessage.success('物流面单已发送至打印队列');
          } catch (blobError) {
            console.error('创建Blob对象错误:', blobError);
            ElMessage.error('无法创建PDF预览: ' + (blobError.message || '未知错误'));
          }
        } else {
          throw new Error('API返回空响应');
        }
      } catch (error) {
        console.error('打印面单错误:', error);
        ElMessage.error('打印面单失败: ' + (error.message || '未知错误'));
      }
    }
  }
}
</script>

<style scoped>
.logistics-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}
</style>
